import React, {Component} from 'react';
import {Button, message, Modal, Tabs} from 'antd';
import './App.css';
import Config from './config';
import Util from './common/util';
import Ajax from './common/ajax';
import IeTips from './common/ieTips/index';
import ShopInfo from './cmpts/shopInfo/index';
import ShopInfoOpts from './cmpts/shopInfoOpts/index';
import MText from './cmpts/mText/index';
import MTextOpts from './cmpts/mTextOpts/index';
import MImage from './cmpts/mImage/index';
import MImageOpts from './cmpts/mImageOpts/index';
import MSwiper from './cmpts/mSwiper/index';
import MSwiperOpts from './cmpts/mSwiperOpts/index';
import GModList from './cmpts/goodsMList/index';
import GModListOpts from './cmpts/goodsMListOpts/index';
import WaiterList from './cmpts/waiterList/index';
import WaiterListOpts from './cmpts/waiterListOpts/index';
import HomeCatList from './cmpts/homeCatList/index';
import HomeCatListOpts from './cmpts/homeCatListOpts/index';
import NearShop from './cmpts/nearShop/index';
import NearShopOpts from './cmpts/nearShopOpts/index';
import ConnectKf from './cmpts/connectKf/index';
import ConnectKfOpts from './cmpts/connectKfOpts/index';
import HomeCardList from './cmpts/homeCardList/index';
import HomeCardListOpts from './cmpts/homeCardListOpts/index';
import MForm from './cmpts/mForm/index';
import MFormOpts from './cmpts/mFormOpts/index';
import MVideo from './cmpts/mVideo/index';
import MVideoOpts from './cmpts/mVideoOpts/index';
import PageList from './cmpts/pageList/index';
import PageOpts from './cmpts/pageOpts/index';
import CmptList from './cmpts/cmptList/index';
import GoodsList from './cmpts/goodsList/index';
import GoodsListOpts from './cmpts/goodsListOpts/index';
import ArtList from './cmpts/artList/index';
import ArtListOpts from './cmpts/artListOpts/index';
import TabBar from './cmpts/tabBar/index';
import TabBarOpts from './cmpts/tabBarOpts/index';
import ShopInfoRow from './cmpts/shopInfoRow/index';
import ShopInfoRowOpts from './cmpts/shopInfoRowOpts/index';
import MImageList from './cmpts/mImageList/index';
import MImageListOpts from './cmpts/mImageListOpts/index';
import MSearch from './cmpts/mSearch/index';
import MSearchOpts from './cmpts/mSearchOpts/index';
import MCase from './cmpts/mCase/index';
import MCaseOpts from './cmpts/mCaseOpts/index';
import MTitle from './cmpts/mTitle/index';
import MTitleOpts from './cmpts/mTitleOpts/index';
import NearShopList from './cmpts/nearShopList/index';
import NearShopListOpts from './cmpts/nearShopListOpts/index';
import Seckill from './cmpts/seckill/index';
import SeckillOpts from './cmpts/seckillOpts/index';
import MUeditor from './cmpts/mUeditor/index';
import MUeditorOpts from './cmpts/mUeditorOpts/index';
import GroupBuy from './cmpts/groupBuy/index';
import GroupBuyOpts from './cmpts/groupBuyOpts/index';
import CutList from './cmpts/cutList/index';
import CutListOpts from './cmpts/cutListOpts/index';
import AgentSearch from './cmpts/agentSearch/index';
import AgentSearchOpts from './cmpts/agentSearchOpts/index';
import MButton from './cmpts/mButton/index';
import MButtonOpts from './cmpts/mButtonOpts/index';
import CateList from './cmpts/cateList/index';
import CateListOpts from './cmpts/cateListOpts/index';

const confirm = Modal.confirm;
const TabPane = Tabs.TabPane;

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            curMod: null, //当前选中组件
            curPageId: '',
            curPage: {},
            page: {},
            pageJson: {},
            pageList: {},
            isModified: false,
            __tabBarSelected: false,
        };

        //0首页专用组件 1.基本组件 2.功能组件 3.高级组件 4.营销组件
        this._cmptsMap = {
            MText: {
                ty: 1,
                isCom: true,
                ref: MText,
                name: '文本'
            },
            MTextOpts: {
                ref: MTextOpts,
            },
            MImage: {
                ty: 1,
                isCom: true,
                ref: MImage,
                name: '图片'
            },
            MImageOpts: {
                ref: MImageOpts,
            },
            MVideo: {
                ty: 1,
                isCom: true,
                ref: MVideo,
                name: '视频'
            },
            MVideoOpts: {
                ref: MVideoOpts
            },
            MSwiper: {
                ty: 0,
                isCom: true,
                ref: MSwiper,
                name: '轮播图'
            },
            MSwiperOpts: {
                ref: MSwiperOpts
            },
            MUeditor: {
                ty: 3,
                isCom: true,
                ref: MUeditor,
                name: '富文本',
            },
            MUeditorOpts: {
                ref: MUeditorOpts
            },
            MImageList: {
                ty: 3,
                isCom: true,
                ref: MImageList,
                name: '图片列表',
            },
            MImageListOpts: {
                ref: MImageListOpts
            },
            MCase: {
                ty: 1,
                isCom: true,
                ref: MCase,
                name: '橱窗',
            },
            MCaseOpts: {
                ref: MCaseOpts
            },
            MTitle: {
                ty: 1,
                isCom: true,
                ref: MTitle,
                name: '标题',
            },
            MTitleOpts: {
                ref: MTitleOpts
            },
            MButton: {
                ty: 1,
                isCom: true,
                ref: MButton,
                name: '按钮',
                minTmplId: 310,
            },
            MButtonOpts: {
                ref: MButtonOpts
            },
            MSearch: {
                ty: 1,
                isCom: true,
                ref: MSearch,
                name: '搜索'
            },
            MSearchOpts: {
                ref: MSearchOpts
            },
            GoodsList: {
                ty: 2,
                isCom: true,
                ref: GoodsList,
                name: '商品列表'
            },
            GoodsListOpts: {
                ref: GoodsListOpts,
            },
            CateList: {
                ty: 2,
                isCom: true,
                isNew: true,
                ref: CateList,
                name: '商品分类',
                minTmplId: 323,
            },
            CateListOpts: {
                ref: CateListOpts
            },
            ArtList: {
                ty: 2,
                isCom: true,
                ref: ArtList,
                name: '文章列表'
            },
            ArtListOpts: {
                ref: ArtListOpts
            },
            MForm: {
                ty: 3,
                isCom: true,
                ref: MForm,
                name: '表单'
            },
            MFormOpts: {
                ref: MFormOpts
            },
            HomeCardList: {
                ty: 4,
                isCom: true,
                ref: HomeCardList,
                name: '优惠券/会员卡'
            },
            HomeCardListOpts: {
                ref: HomeCardListOpts
            },
            WaiterList: {
                ty: 2,
                isCom: true,
                ref: WaiterList,
                name: '技师预约'
            },
            WaiterListOpts: {
                ref: WaiterListOpts
            },
            ShopInfo: {
                ty: 0,
                isCom: true,
                ref: ShopInfo,
                name: '商家信息'
            },
            ShopInfoOpts: {
                ref: ShopInfoOpts
            },
            ShopInfoRow: {
                ty: 0,
                isCom: true,
                ref: ShopInfoRow,
                name: '商家信息2'
            },
            ShopInfoRowOpts: {
                ref: ShopInfoRowOpts
            },
            GModList: {
                ty: 0,
                isCom: true,
                ref: GModList,
                name: '商品/素材块'
            },
            GModListOpts: {
                ref: GModListOpts,
            },
            HomeCatList: {
                ty: 0,
                isCom: true,
                ref: HomeCatList,
                name: '首页分类'
            },
            HomeCatListOpts: {
                ref: HomeCatListOpts
            },
            NearShop: {
                ty: 0,
                isCom: true,
                ref: NearShop,
                name: '附近的店'
            },
            NearShopOpts: {
                ref: NearShopOpts
            },
            NearShopList: {
                ty: 2,
                isCom: true,
                ref: NearShopList,
                name: '门店列表'
            },
            NearShopListOpts: {
                ref: NearShopListOpts
            },
            ConnectKf: {
                ty: 0,
                isCom: true,
                ref: ConnectKf,
                name: '客服'
            },
            ConnectKfOpts: {
                ref: ConnectKfOpts
            },
            TabBar: {
                ty: 3,
                ref: TabBar,
                name: '底部导航'
            },
            TabBarOpts: {
                ref: TabBarOpts
            },
            Seckill: {
                ty: 4,
                isCom: true,
                ref: Seckill,
                name: '秒杀',
                canUseId: '2' //模块可使用的指定id
            },
            SeckillOpts: {
                ref: SeckillOpts
            },
            GroupBuy: {
                ty: 4,
                isCom: true,
                ref: GroupBuy,
                name: '团购',
                canUseId: '3' //模块可使用的指定id
            },
            GroupBuyOpts: {
                ref: GroupBuyOpts
            },
            CutList: {
                ty: 4,
                isCom: true,
                ref: CutList,
                name: '砍价',
                canUseId: '4' //模块可使用的指定id
            },
            CutListOpts: {
                ref: CutListOpts
            },
            AgentSearch: {
                ty: 10,
                isCom: true,
                ref: AgentSearch,
                name: '代理查询'
            },
            AgentSearchOpts: {
                ref: AgentSearchOpts
            }

        };

        this._rendPhoneContent = this._rendPhoneContent.bind(this);
        this._addCmpt = this._addCmpt.bind(this);
        this._selectedCmpt = this._selectedCmpt.bind(this);
        this._delCmpt = this._delCmpt.bind(this);
        this._delAllCmpt = this._delAllCmpt.bind(this);
        this._moveCmpt = this._moveCmpt.bind(this);
        this._optsDataChange = this._optsDataChange.bind(this);
        this._save = this._save.bind(this);
    }

    componentDidMount() {
        this._fetch();
    }

    render() {
        var _self = this;
        var {pageJson, __tabBarSelected, curPage} = this.state;
        var page, pageStyle, tabBar, tabBarMap;

        try {
            page = pageJson.page;
            pageStyle = page.style || {};
            tabBar = page.tabBar || {};
            tabBarMap = page.tabBarMap || {};
        } catch (e) {
            pageStyle = {};
            tabBar = {};
            tabBarMap = {};
        }

        return (
            <div className="qcy-content qcyEditor__wrap">
                <div className="qcyEditor clearfix">
                    <div className="qcyEditor__cmpts">
                        <div className="qcyEditor__save">
                            <Button
                                onClick={() => {
                                    this._save(1)
                                }}
                                type="primary"
                                disabled={!this._isModified()}
                            >保存</Button>
                            {/*<Button*/}
                            {/*onClick={() => {*/}
                            {/*this._preview()*/}
                            {/*}}*/}
                            {/*type="primary"*/}
                            {/*disabled={!this._isModified()}*/}
                            {/*>预览</Button>*/}
                        </div>
                    </div>
                    <div className="qcyEditor__content">
                        <div className="qcyEditor__phoneTop">
                            <img src="/asset/admin/images/editor/phonetop.png"/>
                        </div>
                        <div id="J_phoneContent" className="qcyEditor__phoneContent" style={pageStyle}>
                            {this._rendPhoneContent()}
                        </div>
                        <div className="qcyEditor__phoneBottom">
                            <img src="/asset/admin/images/editor/phonebottom.png"/>
                        </div>
                    </div>

                    {
                        this.state.curMod ?
                            (
                                <div id="J_optsPanelContent" className="qcyEditor__cmptInfo">
                                    {
                                        this.state.curMod ?
                                            <div
                                                className="qcyEditor__cmptInfo__title">{this._cmptsMap[this.state.curMod.name].name}组件</div>
                                            : null
                                    }

                                    {this._getOptsPanel()}

                                    {
                                        this.state.curMod ?
                                            <div className="qcyEditor__cmptInfo__footer">
                                                <Button
                                                    onClick={(e) => {
                                                        this._moveCmpt(e, 'up');
                                                    }}
                                                >上移</Button>
                                                <Button
                                                    onClick={(e) => {
                                                        this._moveCmpt(e, 'down');
                                                    }}
                                                >下移</Button>
                                                <Button
                                                    onClick={this._delCmpt}
                                                >删除</Button>
                                                <Button
                                                    onClick={this._delAllCmpt}
                                                    type="danger"
                                                >清屏</Button>
                                            </div>
                                            : null
                                    }
                                </div>
                            )
                            :
                            (
                                <div id="J_optsPanelContent" className="qcyEditor__cmptInfo">
                                    <div
                                        className="qcyEditor__cmptInfo__title"
                                    >
                                        页面配置
                                    </div>

                                    <PageOpts data={pageJson.page} dataChange={this._pageDataChange.bind(this)}/>
                                </div>
                            )
                    }

                    <div className="qcyEditor__pagesWrap">
                        <Tabs defaultActiveKey="1">
                            <TabPane tab="页面管理" key="1">
                                <PageList onSelect={this._selectPage.bind(this)}/>
                            </TabPane>
                            <TabPane tab="组件库" key="2">
                                {_self._getCmptList()}
                            </TabPane>
                        </Tabs>
                    </div>
                </div>
                <IeTips />
            </div>
        );
    }

    _getCmptList() {
        var _self = this;
        var {curPage, moduleList} = _self.state;
        var cmptData = JSON.parse(JSON.stringify(_self._cmptsMap));

        return (
            <CmptList
                data={cmptData}
                moduleList={moduleList}
                curPage={curPage}
                onAddCmpt={(key) => {
                    _self._addCmpt(key)
                }}
            />
        );
    }

    _fetch() {
        var _self = this;

        Ajax.G('/admin/Home/xcxIndexData', {}, function (res) {
            var d = res['result'];

            Config.global.tmplId = d.template_id;

            _self.setState({
                ShopInfo: {
                    name: d.title,
                    phone: d.contact,
                    weixin: d.weixin,
                    qq: d.qq,
                    address: d.address,
                    time: d.hours,
                    logo: d.logo,
                    shopImg: d.shop_img,
                    shareTitle: d.share_title,
                    kfState: d.kf_state
                },
                ShopInfoRow: {
                    name: d.title,
                    logo: d.logo,
                },
                MSwiper: d.bannerList,
                HomeCatList: d.homeCatSetting,
                GModList: d.goodsModuleList,
                isPay: d.isPay == 1,
                appType: d.app_type,
                moduleList: d.module_list,
                templateId: d.template_id,
            });
        });
    }

    _fetchPageJson(p) {
        var _self = this;
        var {pageList} = this.state;
        if (!p) {
            return;
        }
        var pageId = p.id;

        _self._cancelSelected(); //取消组件选中状态

        pageList[pageId] = p;

        if (!_self._pageMapping) {
            _self._pageMapping = {};
        }
        var _pageJson = _self._pageMapping[pageId];

        if (_pageJson) {
            _self.setState({
                curPageId: pageId,
                curPage: p,
                pageJson: _pageJson,
                curMod: null,
                pageList
            });
            return;
        }

        Ajax.G('/admin/Home/getPageInfo', {
            pageId,
        }, function (res) {
            var data = res['result']['info'];
            var pageJson, pModules, page;
            var oldTabBar, oldTabBarIndex = -1;

            try {
                pageJson = JSON.parse(data['settings']);
            } catch (e) {
                pageJson = {
                    page: {
                        style: {},
                        dataset: {
                            title: p.name,
                            name: p.name,
                        }
                    },
                    pModules: []
                }
            }

            page = pageJson.page;
            if (typeof page.style == 'string') {
                page.style = {};
            }
            if (!page.dataset) {
                page.dataset = {
                    name: p.name,
                    title: '',
                    shareTitle: '',
                    id: p.id,
                    type: p.type,
                };
            }
            page.dataset.id = p.id;
            page.dataset.type = p.type;

            pModules = pageJson['pModules'];

            //特殊处理Video
            pModules.forEach(function (mod, index) {
                var content = mod.content;

                if (mod.name == 'MVideo') {
                    if (content.dataset && content.dataset.url) {
                        // content.dataset.url = encodeURIComponent(content.dataset.url);
                        content.dataset.url = content.dataset.url;
                    }
                }
                if (mod.name == 'TabBar') {
                    oldTabBarIndex = index;
                }
            });

            if (oldTabBarIndex > -1) {
                oldTabBar = pModules.splice(oldTabBarIndex, 1)[0];
            }

            if (p.type == 0 && !page.tabBarMod) { //首页,初始化tabBar
                let {data:tabBarData} = JSON.parse(JSON.stringify(TabBar.defaultProps));
                page.tabBarMod = oldTabBar || {
                        uid: Util.getUId(),
                        name: 'TabBar',
                        content: tabBarData,
                        __data: {}
                    };
            }


            _self._pageMapping[pageId] = pageJson;

            _self.setState({
                curPageId: pageId,
                curPage: p,
                pageJson,
                curMod: null,
                pageList
            });
        });
    }

    //切换页面
    _selectPage(p) {
        this._fetchPageJson(p);
    }

    //检查页面是否有修改
    _isModified() {
        var {pageList} = this.state;

        return Object.keys(pageList).some(function (pageId) {
            return pageList[pageId] && pageList[pageId].isModified;
        })
    }

    /**
     * 渲染手机屏
     * @returns {Array}
     * @private
     */
    _rendPhoneContent() {
        var _self = this;
        var {page = {}, pModules = []} =  this.state.pageJson;
        var tabBarMod = page.tabBarMod;
        var arr = [];
        var appData = {
            appType: this.state.appType || [],
        };

        pModules.forEach(function (mod, i) {
            var Cmpt = _self._cmptsMap[mod.name].ref;
            var content = mod.content;
            var dataset = _self.state[mod.name];

            if (mod.name == 'TabBar') {
                return;
            }
            if (dataset && content) {
                content['dataset'] = dataset;
            }
            arr.push(
                <Cmpt
                    key={'cmptItem' + mod.uid}
                    data={content}
                    app={appData}
                    onSelected={(e) => {
                        _self._selectedCmpt(i)
                    }}
                    selected={mod.__data && mod.__data.selected}
                />
            );
        });

        if (tabBarMod) {
            arr.push(
                <TabBar
                    key={'cmptItem' + tabBarMod.uid}
                    data={tabBarMod.content}
                    app={appData}
                    onSelected={(e) => {
                        _self._selectedCmpt(null, true)
                    }}
                    selected={tabBarMod.__data && tabBarMod.__data.selected}
                />
            );
        }
        return arr;
    }

    /**
     * 获取操作面板
     * @private
     */
    _getOptsPanel() {
        var curMod = this.state.curMod;
        if (!curMod) {
            return null;
        }
        var Cmpt = this._cmptsMap[curMod.name + 'Opts'].ref;

        return (
            <Cmpt key={curMod.uid}
                  data={curMod.content}
                  dataChange={this._optsDataChange}
            />
        );
    }

    /**
     * 面板数据改变后调用
     * @param data
     * @private
     */
    _optsDataChange(data) {
        var {pageJson, curMod, curPageId, pageList} = this.state;

        curMod.content = data;
        pageList[curPageId] && (pageList[curPageId].isModified = true);

        this.setState({
            curMod,
            pageJson,
            pageList,
        })
    }

    //页面配置改变后调用
    _pageDataChange(data) {
        var {pageJson, pageList, curPageId} = this.state;

        pageJson['page'] = data;

        pageList[curPageId] && (pageList[curPageId].isModified = true);

        this.setState({
            pageJson,
            pageList,
        })
    }

    /**
     * 添加组件
     * @param e
     * @param cmptName
     * @private
     */
    _addCmpt(cmptName) {
        var {curPageId, pageList, pageJson, templateId = 1} = this.state;
        var pModules = pageJson.pModules || [];
        var curMod = this.state.curMod;
        var cmptWrap = this._cmptsMap[cmptName];
        var minTmplId = cmptWrap.minTmplId;
        if (templateId && minTmplId && templateId < minTmplId) {
            message.warn(Config.tips.tmplIdLow);
            return;
        }
        var Cmpt = cmptWrap.ref;
        var {data} =  JSON.parse(JSON.stringify(Cmpt.defaultProps));
        var obj = {
            uid: Util.getUId(),
            name: cmptName,
            content: data,
            __data: {}
        };
        var curIndex;

        //唯一性校验
        if (data.isOnly) {
            if (pModules.some(function (mod, index) {
                    return mod.content.type == data.type;
                })) {
                return message.error('该组件页面只能添加一个');
            }
        }

        //支付权限判断
        if (data.needPay && !this.state.isPay) {
            return message.error('您没有开通用户支付权限，无法使用该功能');
        }

        if (curMod) {
            //当前组件之后插入
            pModules.some(function (mod, index) {
                if (mod.uid == curMod.uid) {
                    curIndex = index + 1;
                    pModules.splice(index + 1, 0, obj);
                    return true;
                }
            });
        } else {
            //最后插入
            pModules.push(obj);
            curIndex = pModules.length - 1;
        }

        this._handleSelected(pModules, curIndex);
        pageJson['pModules'] = pModules;
        pageList[curPageId] && (pageList[curPageId].isModified = true);

        this.setState({
            pageJson,
            curMod: obj,
            pageList,
        });
    }

    /**
     * 选中组件
     * @private
     */
    _selectedCmpt(index, isSelTabBar) {
        var {pageJson} = this.state;
        var tabBarMod = pageJson.page.tabBarMod || {};
        var pModules = pageJson.pModules;

        if (!tabBarMod.__data) {
            tabBarMod.__data = {};
        }
        if (isSelTabBar) {
            tabBarMod.__data.selected = true;
            this._handleSelected(pModules, -1);
        } else {
            tabBarMod.__data.selected = false;
            this._handleSelected(pModules, index);
        }
        this.setState({
            curMod: isSelTabBar ? tabBarMod : pModules[index],
            pageJson
        });
    }

    /**
     * 处理选中状态
     * @private
     */
    _handleSelected(pModules, index) {
        if (!pModules) {
            return;
        }
        // if (index < 0) {
        //     index = 0;
        // }
        pModules.forEach(function (mod, i) {
            if (!mod.__data) {
                mod.__data = {};
            }
            mod.__data.selected = i == index;
        });
    }

    /**
     * 取消组件选中状态
     * @private
     */
    _cancelSelected() {
        var {pageJson} = this.state;
        var pModules = pageJson.pModules;

        if (!pModules) {
            return;
        }

        pModules.some(function (mod) {
            if (mod.__data && mod.__data.selected) {
                mod.__data.selected = false
                return true
            }
        })
    }

    /**
     * 删除组件
     * @private
     */
    _delCmpt() {
        var {curPageId, pageList, pageJson, curMod} = this.state;
        var pModules = pageJson.pModules;

        if (curMod.name == 'TabBar') {
            return message.error('底部导航组件不可删除，您可以选择禁用');
        }

        pModules.some(function (mod, index) {
            if (mod.uid == curMod.uid) {
                pModules.splice(index, 1);
                return true;
            }
        });
        pageList[curPageId] && (pageList[curPageId].isModified = true);
        this.setState({
            pageJson,
            curMod: null,
            pageList,
        });
    }

    /**
     * 清空所有组件
     * @private
     */
    _delAllCmpt() {
        var _self = this;

        confirm({
            title: '您确定删除所有组件吗?',
            content: '删除组件，保存后会同步到线上',
            onOk() {
                var {curPageId, pageList, pageJson} = _self.state;

                pageList[curPageId] && (pageList[curPageId].isModified = true);
                pageJson['pModules'] = [];

                _self.setState({
                    pageJson,
                    curMod: null,
                    pageList
                });
            },
            onCancel() {
            },
        });
    }

    /**
     * 上下移动
     * @param e
     * @param direction
     * @private
     */
    _moveCmpt(e, direction) {
        var {curPageId, pageList, pageJson, curMod} = this.state;
        var pModules = pageJson.pModules;
        var num = direction == 'up' ? -1 : 1;

        pModules.some(function (mod, index) {
            if (mod.uid == curMod.uid) {
                pModules.splice(index, 1);
                pModules.splice(index + num, 0, curMod);
                return true;
            }
        });

        pageList[curPageId] && (pageList[curPageId].isModified = true);

        this.setState({
            pageJson,
            pageList
        });
    }

    _preview() {
        Ajax.G('/admin/Home/priviewXcx22', {}, function (result) {
            console.log(result);
        });
    }

    /**
     * 保存/发布
     * @param ty 0保存，1发布
     * @private
     */
    _save(ty) {
        var _self = this;

        confirm({
            title: '您确定保存吗?',
            content: '保存后当前修改将直接同步到线上',
            onOk() {
                var {pageList} = _self.state;
                var _pageMapping = _self._pageMapping;
                var ajaxCount = 0;
                var ajaxSucCount = 0;

                Object.keys(pageList).forEach(function (pageId) {
                    var pageObj = pageList[pageId];
                    if (!pageObj.isModified) {
                        return;
                    }
                    var isHomePage = pageObj.type == 0; //是否是首页
                    var pageJson = JSON.parse(JSON.stringify(_pageMapping[pageId]));
                    var pModules = pageJson.pModules;
                    var tabBarData;

                    if (isHomePage) {
                        tabBarData = pageJson.page.tabBarMod['content']['dataset'];
                    }

                    if (isHomePage) {
                        delete pageJson.page.tabBarMod.__data;
                    }

                    pModules.forEach(function (mod) {
                        delete mod.__data;
                        if (_self.state[mod.name]) {
                            mod.content.dataset = {}
                        }
                    });

                    ajaxCount++

                    Ajax.P('/admin/Home/editPageSettings', {
                        // setData: encodeURIComponent(JSON.stringify(pageJson)),
                        setData: JSON.stringify(pageJson),
                        pageId,
                    }, function () {

                        ajaxSucCount++
                        pageObj.isModified = false

                        if (ajaxSucCount == ajaxCount) {
                            _self.setState({
                                pageList
                            })
                            message.success('保存成功')
                        }
                    });

                    if (isHomePage && tabBarData) {
                        let {tabBar, tabBarMap} = tabBarData;
                        let list = [];
                        var hasCart = 0;

                        tabBar.list.forEach(function (barItem) {
                            if (barItem._deleted) {
                                return;
                            }
                            if (/pages\/cart\/cart/.test(barItem.pagePath)) {
                                hasCart = 1;
                            }
                            list.push(barItem);
                        })
                        tabBar.list = list;
                        tabBarMap.hasCart = hasCart;
                        // tabBarMap.list = list;

                        if (tabBarData.status == '0') { //tabBar已禁用
                            tabBar = {};
                            tabBarMap = {}
                        }
                        Ajax.P('/admin/XcxConfig/customTabbar', {
                            menu_tabbar: JSON.stringify(tabBar),
                            ext_tabbar: JSON.stringify(tabBarMap),
                        }, function () {
                        });
                    }

                })
            },
            onCancel() {
            },
        });
    }
}

export default App;
